#!/bin/env python

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import shlex
import shutil
import subprocess
import sys

"""
Invoke as:

    thrift/compiler/test/build_fixtures [$BUILDDIR]

where $BUILDDIR/thrift/compiler/thrift is the thrift compiler.

If using Buck to build the thrift compiler, the $BUILDDIR default will work.
"""

def ascend_find_exe(path, target):
    if not os.path.isdir(path):
        path = os.path.dirname(path)
    while True:
        test = os.path.join(path, target)
        if os.access(test, os.X_OK):
            return test
        parent = os.path.dirname(path)
        if os.path.samefile(parent, path):
            return None
        path = parent

def ascend_find_dir(path, target):
    if not os.path.isdir(path):
        path = os.path.dirname(path)
    while True:
        test = os.path.join(path, target)
        if os.path.isdir(test):
            return test
        parent = os.path.dirname(path)
        if os.path.samefile(parent, path):
            return None
        path = parent

def read_lines(path):
    with open(path, 'r') as f:
        return f.readlines()

exe = os.path.join(os.getcwd(), sys.argv[0])
buildDir = sys.argv[1] if len(sys.argv) > 1 else 'buck-out/gen'
thriftRel = os.path.join(buildDir, 'thrift/compiler/thrift')
templatesRel = os.path.join(buildDir, 'thrift/compiler/generate/templates')
templates = ascend_find_dir(exe, templatesRel)
thrift = ascend_find_exe(exe, thriftRel)
fixtureDir = ascend_find_dir(exe, 'thrift/compiler/test/fixtures')
fixtureNames = [
    f
    for f in os.listdir(fixtureDir)
    if os.path.isfile(os.path.join(fixtureDir, f, 'cmd'))
]

for name in fixtureNames:
    cwd = os.path.join(fixtureDir, name)
    for fn in set(os.listdir(cwd)) - set(['cmd', 'src']):
        if fn.startswith('.'):
            continue
        shutil.rmtree(os.path.join(cwd, fn))
    cmds = read_lines(os.path.join(cwd, 'cmd'))
    for cmd in cmds:
        args = shlex.split(cmd.strip())
        if args[0].startswith("cpp"):
            path = os.path.join("thrift/compiler/test/fixtures", name)
            extra = "include_prefix=" + path
            join = "," if ":" in args[0] else ":"
            args[0] = args[0] + join + extra
        subprocess.check_call(
            [thrift, "-r", "--templates", templates, "--gen"] + args,
            cwd=cwd,
            close_fds=True,
        )
